//
//  RegisterViewController.m
//  XDCommonApp
//
//  Created by wanglong8889@126.com on 14-3-6.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "RegisterViewController.h"
#import "XDTools.h"
#import "XDHeader.h"
#import "RegistTwoViewController.h"

#define XZB     65
@interface RegisterViewController ()
{
    NSString *isValiedCode;
}
@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isValiedCode = @"";
    [self initViews];
	// Do any additional setup after loading the view.
}
-(void)initViews{
   self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width
                                                                , self.contentView.frame.size.height)];
    _scrollView.scrollEnabled = NO;
    [self.contentView addSubview:_scrollView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPan)];
    [self changeFrameWhenHiddenNavigationBar];
    [self.contentView addGestureRecognizer:tap];
    
    UIImageView *pointView = [[UIImageView alloc] initWithFrame:CGRectMake(122, 22, 72, 11)];
    pointView.image = [UIImage imageNamed:@"first_point"];
    [self.scrollView addSubview:pointView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB, 90,110, 25)];
    titleLabel.text = @"新用户注册";
    titleLabel.font = [UIFont fontWithName:@"Helvetica" size:22.0];
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:titleLabel];
    
    UILabel *registLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB,titleLabel.frame.origin.y+titleLabel.frame.size.height+20,84, 12)];
    registLabel.text = @"用已有账号登陆";
    registLabel.textColor = [UIColor blackColor];
    registLabel.font = [UIFont fontWithName:@"Helvetica" size:12.0];
    registLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:registLabel];
    
    //注册的透明btn
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(registLabel.frame.origin.x-5, registLabel.frame.origin.y-5,registLabel.frame.size.width+10, registLabel.frame.size.height+10);
    [registBtn addTarget:self action:@selector(useHaveName) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:registBtn];
    
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(registLabel.frame.origin.x, registLabel.frame.origin.y+registLabel.frame.size.height, registLabel.frame.size.width, 1)];
    lineView.backgroundColor = [UIColor blackColor];
    [self.scrollView addSubview:lineView];
    
    UILabel *inputLabel = [[UILabel alloc] initWithFrame:CGRectMake(registLabel.frame.origin.x, registLabel.frame.origin.y+registLabel.frame.size.height+44, 187, 15)];
    inputLabel.text = @"请输入您的手机号:";
    inputLabel.font = [UIFont systemFontOfSize:12.0];
    inputLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:inputLabel];
    
    
    userTf = [[UITextField alloc] initWithFrame:CGRectMake(XZB, inputLabel.frame.origin.y+inputLabel.frame.size.height+10,187, 27)];
    userTf.borderStyle = UITextBorderStyleLine;
    userTf.backgroundColor =  RGBA(168, 168, 168, 1.0);
    userTf.placeholder = @"请输入您的账号";
    userTf.textColor = [UIColor whiteColor];

    if (IOS7) {
        userTf.tintColor = [UIColor whiteColor];
        
    }
//    userTf.keyboardType = UIKeyboardTypeNumberPad;
    userTf.delegate = self;
    userTf.font = [UIFont systemFontOfSize:13.0];
    userTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.scrollView addSubview:userTf];

    
    verticalTf = [[UITextField alloc] initWithFrame:CGRectMake(XZB, userTf.frame.origin.y+userTf.frame.size.height+15, 103, 27)];
    verticalTf.borderStyle = UITextBorderStyleLine;
    verticalTf.backgroundColor =  RGBA(168, 168, 168, 1.0);
    verticalTf.placeholder = @"请输入六位验证码";
    if (IOS7) {
        verticalTf.tintColor = [UIColor whiteColor];
        
    }
    verticalTf.textColor = [UIColor whiteColor];
//    verticalTf.secureTextEntry = YES;
    verticalTf.returnKeyType = UIReturnKeyDone;
    verticalTf.delegate = self;
    verticalTf.font = [UIFont systemFontOfSize:13.0];
    verticalTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    verticalTf.placeholder = @"请输入验证码";
    [self.scrollView addSubview:verticalTf];
    

    UIButton *getVerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    getVerBtn.frame = CGRectMake(verticalTf.frame.origin.x+verticalTf.frame.size.width, verticalTf.frame.origin.y, 84, 27);
    [getVerBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getVerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [getVerBtn setBackgroundImage:[UIImage imageNamed:@"get_vertiry"] forState:UIControlStateNormal];
    getVerBtn.titleLabel.font = [UIFont systemFontOfSize:13.5];
    [getVerBtn addTarget:self action:@selector(goVertical) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:getVerBtn];
    
    //服务协议按钮
    UIButton *kuangBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    kuangBtn.frame = CGRectMake(verticalTf.frame.origin.x, verticalTf.frame.origin.y+verticalTf.frame.size.height+30, 18,18);
    [kuangBtn setBackgroundImage:[UIImage imageNamed:@"service_line"] forState:UIControlStateNormal];
    [kuangBtn addTarget:self action:@selector(chanceService) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:kuangBtn];
    

    //服务协议
    UILabel *serviceLabel = [[UILabel alloc] initWithFrame:CGRectMake(kuangBtn.frame.origin.x+kuangBtn.frame.size.width+9,kuangBtn.frame.origin.y+2,49, 12)];
    serviceLabel.text = @"服务协议";
    serviceLabel.font = [UIFont fontWithName:@"Helvetica" size:12.0];
    serviceLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:serviceLabel];
    
    //注册的透明btn
    UIButton *serviceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    serviceBtn.frame = CGRectMake(serviceLabel.frame.origin.x-5, serviceLabel.frame.origin.y-5,serviceLabel.frame.size.width+10, serviceLabel.frame.size.height+10);
    [serviceBtn addTarget:self action:@selector(lookService) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:serviceBtn];
    
    
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(serviceLabel.frame.origin.x, serviceLabel.frame.origin.y+serviceLabel.frame.size.height, serviceLabel.frame.size.width, 1)];
    lineView1.backgroundColor = [UIColor blackColor];
    [self.scrollView addSubview:lineView1];
    
    
    UILabel *continueLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB+132, verticalTf.frame.origin.y+verticalTf.frame.size.height+31, 30,15)];
    continueLabel.text = @"继续";
    continueLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
    continueLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:continueLabel];
    
    UIImageView *arImageView = [[UIImageView alloc] initWithFrame:CGRectMake(continueLabel.frame.origin.x+continueLabel.frame.size.width+6, continueLabel.frame.origin.y-2, 12, 18)];
    arImageView.image = [UIImage imageNamed:@"launh_sure"];
    [self.scrollView addSubview:arImageView];
    
    UIButton *continueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    continueBtn.frame = CGRectMake(XZB+130, verticalTf.frame.origin.y+verticalTf.frame.size.height+26, 50,28);
    [continueBtn addTarget:self action:@selector(continueNex) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:continueBtn];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 0, 45, 45);
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *bImageView = [[UIImageView alloc] initWithFrame:CGRectMake(24, 17, 11, 18)];
    bImageView.image = [UIImage imageNamed:@"left_back"];
    [self.scrollView addSubview:bImageView];
    [self.scrollView addSubview:backBtn];
    

    


}


//用已有账号登陆
-(void)useHaveName{
    [self.navigationController popViewControllerAnimated:YES];
}
//点击获取验证码
-(void)goVertical{
    if (userTf.text.length!=0) {
        if ([self checkPhoneIsNum:userTf.text]) {
            if ([XDTools NetworkReachable]){
                NSString *body = [NSString stringWithFormat:@" <RegisterGetValidate xmlns=\"http://tempuri.org/\">"
                                  "<telno>%@</telno>"
                                  "</RegisterGetValidate>",userTf.text];
                
                __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:REGISTERGETVALIDATE];
                [request setCompletionBlock:^{
                    [XDTools hideProgress:self.contentView];
                    //[XDTools hideProgress:self.contentView];
                    NSString *responseString = [request responseString];
                    // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
                    DDLOG(@"responseString:%@", responseString);
                    
                    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                    int statusCode = [request responseStatusCode];
                    NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
                    
                    NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
                    int count = [arraySOAP count] - 1;
                    NSString *methodName = [arraySOAP objectAtIndex:count];
                    
                    // Use when fetching text data
                    NSString *result = nil;
                    if (statusCode == 200) {
                        //表示正常请求
                        result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                        NSDictionary  *responseDict = [XDTools JSonFromString:result];
                        DDLOG(@"respodic = %@",responseDict);
                        if ([[responseDict objectForKey:@"code"] intValue]==0){
                            isValiedCode = [responseDict objectForKey:@"Vcode"];
                            [XDTools showTips:@"验证码已发到您手机上" toView:self.contentView];
                            
                        }else{
                            [XDTools showTips:@"获取失败，该账号已被注册" toView:self.contentView];
                        }
                    }
                }];
                
                [request setFailedBlock:^{
                    [XDTools hideProgress:self.contentView];
                }];
                
                [request startAsynchronous];
                [XDTools showProgress:self.contentView];
            }else{
                [XDTools showTips:brokenNetwork toView:self.contentView];
            }
            
        }else{
            [XDTools showTips:@"请输入正确的手机号" toView:self.contentView];
        }
      }
        else{
        [XDTools showTips:@"账号不能为空" toView:self.contentView];
    }

}
//服务按钮
-(void)chanceService{
    
}
//查看服务协议
-(void)lookService{
    
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [UIView animateWithDuration:.3 animations:^{
        if (IOS7) {
            self.scrollView.contentOffset = CGPointMake(0, 45);
        }else{
            self.scrollView.contentOffset = CGPointMake(0, 100);
        }
    }];

    return  YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self cancelPan];
    return YES;
}
//继续
-(void)continueNex{

    if (![isValiedCode isEqualToString:verticalTf.text]) {

        [XDTools showTips:@"验证码错误" toView:self.contentView];

        return;
    }
    if (userTf.text.length!=0&&verticalTf.text.length!=0) {
        if ([XDTools NetworkReachable]){
            NSString *body = [NSString stringWithFormat:@" <RegisterOne xmlns=\"http://tempuri.org/\">"
                              "<phone>%@</phone>"
                              "<validate>%@</validate>"
                              "</RegisterOne>",userTf.text,verticalTf.text];
            
            __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:REGISTERONE];
            [request setCompletionBlock:^{
                [XDTools hideProgress:self.contentView];
                //[XDTools hideProgress:self.contentView];
                NSString *responseString = [request responseString];
                // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
                DDLOG(@"responseString:%@", responseString);
                
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                int statusCode = [request responseStatusCode];
                NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
                
                NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
                int count = [arraySOAP count] - 1;
                NSString *methodName = [arraySOAP objectAtIndex:count];
                
                // Use when fetching text data
                NSString *result = nil;
                if (statusCode == 200) {
                    //表示正常请求
                    result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                    NSDictionary  *responseDict = [XDTools JSonFromString:result];
                    DDLOG(@"respodic = %@",responseDict);
                    if ([[responseDict objectForKey:@"code"] intValue]==0){
                        [WLSingleton sharedManager].Uid = [responseDict objectForKey:@"Uid"];
                        [WLSingleton sharedManager].phoneName = userTf.text;
                        RegistTwoViewController *registVC = [[RegistTwoViewController alloc] init];
                        [self.navigationController pushViewController:registVC animated:YES];
                    }else{
                        [XDTools showTips:@"验证码错误" toView:self.contentView];
                    }
                }
            }];
            
            [request setFailedBlock:^{
                [XDTools hideProgress:self.contentView];
            }];
            
            [request startAsynchronous];
            [XDTools showProgress:self.contentView];
        }else{
            [XDTools showTips:brokenNetwork toView:self.contentView];
        }
        
    }else{
        [XDTools showTips:@"内容不能为空" toView:self.contentView];
    }
    
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)cancelPan{
    [userTf resignFirstResponder];
    [verticalTf resignFirstResponder];
    [UIView animateWithDuration:.3 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }];

}


//校验电话是否是数字

-(BOOL)checkPhoneIsNum:(NSString *)str{
    [NSCharacterSet decimalDigitCharacterSet];
    
    
    if ([str stringByTrimmingCharactersInSet: [NSCharacterSet decimalDigitCharacterSet]].length >0) {
        
        //        DLog(@"不是纯数字");
        return NO;
        
    }else{
        if ([str length] == 11) {
             return YES;
        }else{
            return NO;
        }
       
        //        DLog(@"纯数字！");
        
    }
}

//校验邮箱

-(BOOL)isValidateEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
